package com.vf.cloud.common.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

public class EncryptUtil {
	
	
    private static PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();

    /**
     * 密码加密
     *
     * @param raw String 原始密码
     * @return String 加密后的密码
     */
    public static String encrypt(String raw) {
        return passwordEncoder.encode(raw);
    }

    /**
     * 密码校验
     *
     * @param raw String 原始密码
     * @param encodePassword String 加密后的密码
     * @return true | false
     */
    public static boolean matches(String raw, String encodePassword) {
        return passwordEncoder.matches(raw, encodePassword);
    }


	/**
	 * MD5加密字符串
	 * @param str
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 */
	public static String md5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		md5.update((str).getBytes("UTF-8"));
		byte b[] = md5.digest();

		int i;
		StringBuffer buf = new StringBuffer("");

		for (int offset = 0; offset < b.length; offset++) {
			i = b[offset];
			if (i < 0) {
				i += 256;
			}
			if (i < 16) {
				buf.append("0");
			}
			buf.append(Integer.toHexString(i));
		}

		return buf.toString();
	}
	


}
